package com.max.sportmanage.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.max.sportmanage.common.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: java-sport-manage
 * @description:未登录和token过期时访问资源
 * @author: max-qaq
 * @create: 2021-10-23 16:09
 **/

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest Request, HttpServletResponse Response, AuthenticationException e) throws IOException, ServletException {
        Response.setStatus(401);
        Response.setCharacterEncoding("UTF-8");
        Response.setContentType("application/json");
        PrintWriter writer = Response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(Result.FAIL("未登录！请登录后操作")));
        writer.flush();
        writer.close();
    }
}
